package com.nlp.server.config;

import com.nlp.server.interceptor.HeaderInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 拦截器配置
 *
 * @author shiliuyinzhen
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /** 不需要拦截地址 */
    public static final String[] excludeUrls = { "/login", "/logout", "/refresh","/sse/*"};

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getHeaderInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(excludeUrls)
                .order(-10);
    }

    /**
     * 添加静态资源，接口文档
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** swagger-ui 地址 */
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");

        /** knife4j */
        registry.addResourceHandler("/doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 解决跨域问题，全局跨域
     * 在使用拦截器时不能使用WebMvcConfigurer跨域配置，拦截器是会让跨域配置失效
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //放行哪些原始域
//                .allowedOrigins("*")
                //解决跨域配置中的.allowedOrigins不再可用
                //设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                .allowedHeaders("*")
                // 是否发送Cookie
                .allowCredentials(true)
                .allowedMethods("GET", "POST",  "DELETE", "PUT", "OPTIONS")
                .maxAge(3600);
    }


    /**
     * 自定义请求头拦截器
     */
    public HeaderInterceptor getHeaderInterceptor() {
        return new HeaderInterceptor();
    }
}
